package blingking.jfinal.orm.autoconfigure;

import blingking.jfinal.orm.datasource.JFinalORMDataSource;
import blingking.jfinal.orm.properties.JFinalORMDataSourceProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.util.Map;
/**
 * @author King
 * @description
 * @Date 2020/3/22
 */
@Configuration
@ConditionalOnClass(DataSource.class)
@AutoConfigureBefore({JFinalORMAutoConfiguration.class, DataSourceAutoConfiguration.class})
@EnableConfigurationProperties(JFinalORMDataSourceProperties.class)
@ConditionalOnProperty(name = "jfinal.orm.datasource-enable",havingValue = "true")
public abstract class JFinalORMDataSourceAutoConfiguration {


    @Autowired
    JFinalORMDataSourceProperties jFinalORMDataSourceProperties;


    @PostConstruct
    @Bean(JFinalORMDataSource.DATASOURCE_NAME)
    public JFinalORMDataSource initDataSource() {
        Map<String, DataSourceProperties> dataSourcePropertiesMap = jFinalORMDataSourceProperties.getDatasource();
        if (dataSourcePropertiesMap != null && dataSourcePropertiesMap.size() > 0) {
            return JFinalORMDataSource.getInstance().build(dataSourcePropertiesMap);
        } else {
            throw new RuntimeException("Please Config JFinal ORM DataSource");
        }
    }
}

